/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;

/**
 *
 * @author aaron
 */
public class LogServer {
    private static int id = 0;

    public static void main (String [] args) throws IOException {

	//Get the port and created a socket there.
	int port = 8190;
	if (args.length > 0)
	    port = Integer.parseInt(args[0]);
	ServerSocket listener = new ServerSocket(port);
	System.out.println("The Log Server is running on port " + port);

	// Listen for clients. Start a new handler for each.
	// Add each client to the linked list.
	while (true) {
	    Socket client = listener.accept();
	    new LogServerThread(client).start();
	    System.out.println("New client no."+id+
			       " on client's port "+client.getPort());
	    id++;
	}
    }

    
}

class LogServerThread extends Thread {

        private LogReader reader = null;
        private BufferedReader in;
        private PrintWriter out;
        private Socket toClient;
        private String name;

        LogServerThread(Socket s) {
            toClient = s;
        }

        public void run() {
            try {

                // Create i-o streams through the socket we were
                // given when the thread was instantiated
                // and welcome the new client.

                out = new PrintWriter(toClient.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader((toClient.getInputStream())));
                String serverId = in.readLine();
                System.out.println("Recieved server id " + serverId + " from " + toClient.getInetAddress().toString());
                reader = new LogReader(serverId);

                while (toClient.isConnected()) {
                    String s = in.readLine().trim();
                    reader.inputLine(s);
                }
                toClient.close();
            } catch (Exception e) {
                System.out.println("Socket read error:" + e);
            }
        }
    }
